package com.gxa.finance.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxa.common.commons.JsonResult;
import com.gxa.common.commons.R;
import com.gxa.finance.pojo.Flow;
import com.gxa.finance.service.FlowService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@RestController
@RequestMapping("/finance/flow")
@Slf4j
public class FlowController {

    @Autowired
    private FlowService flowService;


    //添加或更新流水
    @CacheEvict(value = "flowList",allEntries=true) //清空指定的缓存
    @PostMapping(value = "/addOrUpdateFlow")
    public R addOrUpdateFlow(@RequestBody Flow flow){

        R r = new R();
        try{
            flowService.saveOrUpdate(flow);
            r.setCode(200);
            r.setMsg("success");
            log.info("添加或更新流水成功");
        }
        catch(Exception e){
            e.printStackTrace();
            r.setCode(401);
            r.setMsg("系统开小差，请联系管理员");
            log.info("添加或更新流水失败");
        }
        return r;
    }


    //删除流水
    @CacheEvict(value = "flowList",allEntries=true) //清空指定的缓存
    @PostMapping(value = "/deleteFlow")
    public R deleteFlow(Integer id){

        R r = new R();
        try{
            flowService.removeById(id);
            r.setCode(200);
            r.setMsg("success");
            log.info("删除流水成功");
        }
        catch(Exception e){
            e.printStackTrace();
            r.setCode(401);
            r.setMsg("系统开小差，请联系管理员");
            log.info("删除流水失败");
        }
        return r;
    }


    //查询流水
    @GetMapping(value = "/queryFlow")
    @Cacheable(value = "flowList") //将方法的返回结果同步到缓存
    public JsonResult queryFlow(@RequestParam Map<String, Object> map) {

        JsonResult jsonResult = new JsonResult();
        try{
            //参数处理
            int currentPage = Integer.parseInt(map.get("currentPage").toString());
            int pageSize = Integer.parseInt(map.get("pageSize").toString());

            //查询的where条件
            QueryWrapper<Flow> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(map.get("orderId")!=null && !map.get("orderId").toString().isEmpty(),"order_id",map.get("orderId"))
                    .eq(map.get("orderType")!=null && !map.get("orderType").toString().isEmpty(),"order_type",map.get("orderType"))
                    .eq(map.get("type")!=null && !map.get("type").toString().isEmpty(),"type",map.get("type"))
                    .eq(map.get("payType")!=null && !map.get("payType").toString().isEmpty(),"pay_type",map.get("payType"))
                    .ge(map.get("startTime")!=null && !map.get("startTime").toString().isEmpty(),"pay_time",map.get("startTime"))
                    .le(map.get("endTime")!=null && !map.get("endTime").toString().isEmpty(),"pay_time",map.get("endTime"));

            //分页信息
            Page<Flow> page = new Page<>(currentPage,pageSize);
            Page<Flow> resultList = flowService.page(page, queryWrapper);

            //响应信息
            jsonResult.setCode(200);
            jsonResult.setMsg("success");
            jsonResult.setCount((int) resultList.getTotal());
            jsonResult.setData(resultList.getRecords());
            log.info("查询流水成功");
        }
        catch(Exception e){
            e.printStackTrace();
            jsonResult.setCode(401);
            jsonResult.setMsg("系统开小差，请联系管理员");
            log.info("查询流水失败");
        }

        return  jsonResult;
    }


    //导出到excel
    @GetMapping(value = "/exportToExcel")
    public void exportToExcel(@RequestParam Map<String,Object> map, HttpServletResponse response){

        R r = new R();

        try {
            //参数处理
            int currentPage = Integer.parseInt(map.get("currentPage").toString());
            int pageSize = Integer.parseInt(map.get("pageSize").toString());
            //查询的where条件和要查询的字段
            //查询的where条件和要查询的字段
            QueryWrapper<Flow> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(map.get("orderId")!=null && !map.get("orderId").toString().isEmpty(),"order_id",map.get("orderId"))
                    .eq(map.get("orderType")!=null && !map.get("orderType").toString().isEmpty(),"order_type",map.get("orderType"))
                    .eq(map.get("type")!=null && !map.get("type").toString().isEmpty(),"type",map.get("type"))
                    .eq(map.get("payType")!=null && !map.get("payType").toString().isEmpty(),"pay_type",map.get("payType"))
                    .eq(map.get("payTime")!=null,"pay_time",map.get("payTime"));
            //分页信息
            Page<Flow> page = new Page<>(currentPage,pageSize);
            Page<Flow> resultList = flowService.page(page, queryWrapper);
            //获取数据
            List<Flow> flowList = resultList.getRecords();

            //数据封装
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("资金流水记录","流水表"), Flow.class, flowList);

            //创建文件名称
            Date currentDate = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String str = simpleDateFormat.format(currentDate);
            String filename = str + ".xls";

            //设置响应头和编码格式
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            //通过输出流输出文件
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
            log.info("数据导出成功");
        }
        catch (Exception e) {
            e.printStackTrace();
            r.setCode(401);
            r.setMsg("系统开小差，请联系管理员");
            log.info("数据导出失败");
        }
    }
}
